package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.vo.GoodsVo;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author stone
 * @date 2023/03/20 09:38
 */
public class GoodsServiceImpl implements GoodsService {

    private BrandService brandService = new BrandServiceImpl();
    private CategoryService categoryService = new CategoryServiceImpl();
    private SpecificationService specificationService = new SpecificationServiceImpl();
    private GoodsAttributeService attributeService = new GoodsAttributeServiceImpl();
    private GoodsProductService productService = new GoodsProductServiceImpl();

    @Override
    public BaseRespVo create(GoodsVo goodsVo) {
        TransactionUtil.startTransaction();
        try {
            BaseRespVo error = validate(goodsVo);
            if (error != null) {
                return error;
            }

            MarketGoods goods = goodsVo.getGoods();
            MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
            MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();
            MarketGoodsProduct[] products = goodsVo.getProducts();

            String name = goods.getName();
            if (this.checkExistByName(name)) {
                return BaseRespVo.fail(611, "商品名已经存在");
            }

            // 商品表里面有一个字段retailPrice记录当前商品的最低价
            BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
            for (MarketGoodsProduct product : products) {
                BigDecimal productPrice = product.getPrice();
                if(retailPrice.compareTo(productPrice) == 1){
                    retailPrice = productPrice;
                }
            }
            goods.setRetailPrice(retailPrice);

            // 商品基本信息表market_goods
            this.add(goods);


            // 商品规格表market_goods_specification
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setId(null);
                specificationService.add(specification);
            }

            // 商品参数表market_goods_attribute
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setId(null);
                attributeService.add(attribute);
            }

            // 商品货品表market_product
            for (MarketGoodsProduct product : products) {
                product.setId(null);
                product.setGoodsId(goods.getId());
                productService.add(product);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            TransactionUtil.rollback();
        }
        TransactionUtil.commit();
        return BaseRespVo.ok();
    }

    @Override
    public boolean checkExistByName(String name) {
        MarketGoodsMapper goodsMapper = MyBatisUtil.getSqlSession().getMapper(MarketGoodsMapper.class);
        MarketGoodsExample example = new MarketGoodsExample();
        example.or().andNameEqualTo(name).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        return goodsMapper.countByExample(example) != 0;
    }

    @Override
    public int add(MarketGoods goods) {
        MarketGoodsMapper goodsMapper = TransactionUtil.getMapper(MarketGoodsMapper.class);
        Date now = new Date();
        goods.setAddTime(now);
        goods.setUpdateTime(now);
        return goodsMapper.insertSelective(goods);
    }

    private BaseRespVo validate(GoodsVo goodsVo) {
        MarketGoods goods = goodsVo.getGoods();
        String name = goods.getName();
        if (StringUtil.isEmpty(name)) {
            return BaseRespVo.badArgument();
        }
        String goodsSn = goods.getGoodsSn();
        if (StringUtil.isEmpty(goodsSn)) {
            return BaseRespVo.badArgument();
        }
        // 品牌商可以不设置，如果设置则需要验证品牌存在
        Integer brandId = goods.getBrandId();
        if (brandId != null && brandId != 0) {
            if (brandService.findById(brandId) == null) {
                return BaseRespVo.badArgument();
            }
        }
        // 商品类目可以不设置，如果设置则需要验证商品类目存在
        Integer categoryId = goods.getCategoryId();
        if (categoryId != null && categoryId != 0) {
            if (categoryService.findById(categoryId) == null) {
                return BaseRespVo.badArgument();
            }
        }

        MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            String attr = attribute.getAttribute();
            if (StringUtil.isEmpty(attr)) {
                return BaseRespVo.badArgument();
            }
            String value = attribute.getValue();
            if (StringUtil.isEmpty(value)) {
                return BaseRespVo.badArgument();
            }
        }

        MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();
        for (MarketGoodsSpecification specification : specifications) {
            String spec = specification.getSpecification();
            if (StringUtil.isEmpty(spec)) {
                return BaseRespVo.badArgument();
            }
            String value = specification.getValue();
            if (StringUtil.isEmpty(value)) {
                return BaseRespVo.badArgument();
            }
        }

        MarketGoodsProduct[] products = goodsVo.getProducts();
        for (MarketGoodsProduct product : products) {
            Integer number = product.getNumber();
            if (number == null || number < 0) {
                return BaseRespVo.badArgument();
            }

            BigDecimal price = product.getPrice();
            if (price == null) {
                return BaseRespVo.badArgument();
            }

            String[] productSpecifications = product.getSpecifications();
            if (productSpecifications.length == 0) {
                return BaseRespVo.badArgument();
            }
        }

        return null;
    }
}
